<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
const path = require('path');
const webpack = require('webpack');
const { merge } = require('webpack-merge');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
<%_ if (enableTranslation) { _%>
const { hashElement } = require('folder-hash');
const MergeJsonWebpackPlugin = require('merge-jsons-webpack-plugin');
<%_ } _%>
const utils = require('./utils.js');
const environment = require('./environment');

const getTsLoaderRule = () => {
  return [
    {
      loader: 'thread-loader',
      options: {
        // There should be 1 cpu for the fork-ts-checker-webpack-plugin.
        // The value may need to be adjusted (e.g. to 1) in some CI environments,
        // as cpus() may report more cores than what are available to the build.
        workers: require('os').cpus().length - 1,
      },
    },
    {
      loader: 'ts-loader',
      options: {
        transpileOnly: true,
        happyPackMode: true,
      },
    },
  ];
};

module.exports = async options => {
  const development = options.env === 'development';
<%_ if (enableTranslation) { _%>
  const languagesHash = await hashElement(path.resolve(__dirname, '../<%= this.relativeDir(clientRootDir, clientSrcDir) %>i18n'), {
    algo: 'md5',
    encoding: 'hex',
    files: { include: ['*.json'] },
  });

<%_ } _%>
return merge(
{
  cache: {
    // 1. Set cache type to filesystem
    type: 'filesystem',
    cacheDirectory: path.resolve(__dirname, '../<%= this.relativeDir(clientRootDir, temporaryDir) %>webpack'),
    buildDependencies: {
      // 2. Add your config as buildDependency to get cache invalidation on config change
      config: [
        __filename,
        path.resolve(__dirname, `webpack.${development ? 'dev' : 'prod'}.js`),
        path.resolve(__dirname, 'environment.js'),
        path.resolve(__dirname, 'utils.js'),
        path.resolve(__dirname, '../postcss.config.js'),
        path.resolve(__dirname, '../tsconfig.json')
      ],
    },
  },
  resolve: {
    extensions: [
      '.js', '.jsx', '.ts', '.tsx', '.json'
    ],
    modules: ['node_modules'],
    alias: utils.mapTypescriptAliasToWebpackAlias(),
    fallback: {
      path: require.resolve('path-browserify'),
    },
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: getTsLoaderRule(options.env),
        include: [utils.root('./<%= this.relativeDir(clientRootDir, clientSrcDir) %>app')],
        exclude: [utils.root('node_modules')]
      },
      {
        enforce: 'pre',
        test: /\.jsx?$/,
        loader: 'source-map-loader'
      }
    ]
  },
  stats: {
    children: false
  },
  plugins: [
    new webpack.EnvironmentPlugin({
      // react-jhipster requires LOG_LEVEL config.
      LOG_LEVEL: development ? 'info' : 'error',
    }),
    new webpack.DefinePlugin({
<%_ if (enableTranslation) { _%>
      I18N_HASH: JSON.stringify(languagesHash.hash),
<%_ } _%>
      DEVELOPMENT: JSON.stringify(development),
      VERSION: JSON.stringify(environment.VERSION),
      SERVER_API_URL: JSON.stringify(environment.SERVER_API_URL),
    }),
    new ESLintPlugin({
      configType: 'flat',
      extensions: ['ts', 'tsx'],
    }),
    new ForkTsCheckerWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [
<%_ if (applicationTypeGateway || applicationTypeMonolith) { _%>
        {
          // https://github.com/swagger-api/swagger-ui/blob/v4.6.1/swagger-ui-dist-package/README.md
          context: require('swagger-ui-dist').getAbsoluteFSPath(),
          from: '*.{js,css,html,png}',
          to: 'swagger-ui/',
          globOptions: { ignore: ['**/index.html'] },
        },
        {
          from: path.join(path.dirname(require.resolve('axios/package.json')), 'dist/axios.min.js'),
          to: 'swagger-ui/',
        },
        { from: './<%= this.relativeDir(clientRootDir, clientSrcDir) %>swagger-ui/', to: 'swagger-ui/' },
<%_ } _%>
        { from: './<%= this.relativeDir(clientRootDir, clientSrcDir) %>content/', to: 'content/' },
        { from: './<%= this.relativeDir(clientRootDir, clientSrcDir) %>favicon.ico', to: 'favicon.ico' },
        { from: './<%= this.relativeDir(clientRootDir, clientSrcDir) %>manifest.webapp', to: 'manifest.webapp' },
        // jhipster-needle-add-assets-to-webpack - JHipster will add/remove third-party resources in this array
        { from: './<%= this.relativeDir(clientRootDir, clientSrcDir) %>robots.txt', to: 'robots.txt' }
      ],
    }),
    new HtmlWebpackPlugin({
      template: './<%= this.relativeDir(clientRootDir, clientSrcDir) %>index.html',
      chunksSortMode: 'auto',
      inject: 'body',
      base: '/',
    }),
<%_ if (enableTranslation) { _%>
    new MergeJsonWebpackPlugin({
      output: {
        groupBy: [
          // jhipster-needle-i18n-language-webpack - JHipster will add/remove languages in this array
        ],
      },
    }),
<%_ } _%>
  ],
}
// jhipster-needle-add-webpack-config - JHipster will add custom config
);
};
